from datetime import datetime
from app.logger import get_logger

logger = get_logger('log_query')

def get_error_logs(es_client, index_pattern, start_time, end_time, keyword='ERROR', message_field='message', size=2000):
    """
    从Elasticsearch查询指定时间范围内包含关键字的日志。
    :param es_client: ESClient实例
    :param index_pattern: 索引模式
    :param start_time: datetime对象
    :param end_time: datetime对象
    :param keyword: 检索关键字，默认'ERROR'
    :param message_field: 日志内容字段名，默认'message'
    :param size: 返回最大条数
    :return: 命中日志列表
    """
    print(f"查询时间范围: {start_time} ~ {end_time}")
    query = {
        "query": {
            "bool": {
                "must": [
                    {
                        "range": {
                            "@timestamp": {
                                "gte": start_time.isoformat(),
                                "lt": end_time.isoformat()
                            }
                        }
                    },
                    {
                        "match": {
                            message_field: keyword
                        }
                    }
                ]
            }
        },
        "size": size,
        "sort": [
            {"@timestamp": {"order": "desc"}}
        ]
    }
    try:
        response = es_client.search(index=index_pattern, body=query)
        logger.info(f"查询ES索引[{index_pattern}]，命中{len(response['hits']['hits'])}条错误日志")
        return response['hits']['hits']
    except Exception as e:
        logger.error(f"查询Elasticsearch时出错: {e}")
        return [] 

def get_error_logs2(es_client, index_pattern, start_time, end_time, size=2000):
    query = {
        "query": {
            "bool": {
                "must": [
                    {
                        "range": {
                            "@timestamp": {
                                "gte": start_time.isoformat(),
                                "lt": end_time.isoformat()
                            }
                        }
                    },
                    {
                        "query_string": {
                            "query": 'ERROR AND NOT "json:"',
                            "default_field": "message"
                        }
                    }
                ]
            }
        },
        "size": size,
        "sort": [
            {"@timestamp": {"order": "desc"}}
        ]
    }
    response = es_client.search(index=index_pattern, body=query)
    return response['hits']['hits']

def get_error_logs3(es_client, index_pattern, start_time, end_time, pageIndex=1, size=2000):
    query = {
        "query": {
            "bool": {
                "must": [
                    {
                        "range": {
                            "@timestamp": {
                                "gte": start_time.isoformat(),
                                "lt": end_time.isoformat()
                            }
                        }
                    },
                    {
                        "query_string": {
                            "query": 'ERROR AND NOT "json:"',
                            "default_field": "message"
                        }
                    }
                ]
            }
        },
        "from": max(0, (pageIndex - 1)) * size,
        "size": size,
        "sort": [
            {"@timestamp": {"order": "desc"}}
        ]
    }
    try:
        response = es_client.search(index=index_pattern, body=query)
        hits = response['hits']['hits']
        total = response['hits']['total']['value'] if 'total' in response['hits'] else len(hits)
        return hits, total
    except Exception as e:
        logger.error(f"查询Elasticsearch时出错: {e}")
        return [], 0